//
//  ViewController.m
//  XMPPChat
//
//  Created by 123 on 2017/12/14.
//  Copyright © 2017年 123. All rights reserved.
//

#import "ChatViewController.h"
#import "CSMessageCell.h"
#import "CSMessageModel.h"
#import "CSBigView.h"
#import "EmojiView.h"
#import "CSRecord.h"
#import "UITextView+Category.h"
#import "SDWebImageDownloader.h"
#import "SDImageCache.h"
#import "MMProgressHUD.h"
#import "AFNetworking.h"


#define ScreenWidth  [UIScreen mainScreen].bounds.size.width
#define ScreenHight [UIScreen mainScreen].bounds.size.height

@interface ChatViewController ()<UITextViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,CSMessageCellDelegate, EmojiViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) CGFloat nowHeight;
@property (nonatomic, strong) UIImageView *photoImageView;
@property (nonatomic, strong) CSBigView *bigImageView;
@property (nonatomic, strong) EmojiView *ev;
@property (nonatomic, strong) UIImage *photoImage;
@property (nonatomic, strong) NSIndexPath *selectIndex;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableBottomConstraint;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) UITextView *textView;

@end

@implementation ChatViewController

+ (instancetype)initstance
{
    return [[UIStoryboard storyboardWithName:@"Chat" bundle:nil] instantiateInitialViewController];
}

- (void)requestChatList
{
    [MMProgressHUD showWithTitle:@""];

    NSString *apiName = @"/api/chat_messages";
    
    NSDictionary *userInfo = @{@"type" : @"visit",
                               @"visit_id" : [NSNumber numberWithInteger:self.visit_id],
                               @"page" : [NSNumber numberWithInteger:self.pageIndex],
                               @"size" : [NSNumber numberWithInteger:150]
                               };
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:apiName withBody:userInfo withMethod:YTKRequestMethodGET];
    
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        [MMProgressHUD dismiss];
        NSArray *array = [data valueForKey:@"messages"];
        [self setUpUserData:array];
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        [MMProgressHUD dismiss];
    }];
}


- (void)requestPostMessage:(NSNumber *)imageUrl
{
    NSString *content = _textView.text;
    if (!imageUrl) {
        if (content.length==0) {
            return;
        }
    }
    NSString *apiName = @"/api/chat_send_message";
    
    NSDictionary *userInfo = @{@"type" : @"visit",
                               @"visit_id" : [NSNumber numberWithInteger:self.visit_id],
                               @"content" : content
                               };
    if (imageUrl) {
        userInfo = @{@"type" : @"visit",
                     @"visit_id" : [NSNumber numberWithInteger:self.visit_id],
                     @"image_ids" : @[imageUrl]
                     };
    }
    LPTBaseRequest *request = [[LPTBaseRequest alloc] initWithApi:apiName withBody:userInfo withMethod:YTKRequestMethodPOST];
    
    [request startRequestCompleteSuccess:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
        NSLog(@"Send Success !!");
        
    } completeFailed:^(__kindof LPTBaseRequest * _Nullable request, id  _Nonnull data, NSInteger code) {
        
    }];
}

// make the chat data
- (void)setUpUserData:(NSArray *)arr
{
    for (int i=0; i<arr.count; i++) {
        NSDictionary *dict = arr[i];
        NSString *content = [dict valueForKey:@"content"];
        NSArray *images = [dict valueForKey:@"images"];
        NSString *receiver_type = [dict valueForKey:@"receiver_type"];
        
        //NSDictionary *receiver = [dict valueForKey:@"receiver"];
        
        CSMessageModel *model = [[CSMessageModel alloc] init];
        model.showMessageTime = NO;
        //model.messageTime = @"2017年12月12日 16:37";
        NSString *logo_url = @"";
        if ([receiver_type isEqualToString:@"user"]) {
            model.messageSenderType = MessageSenderTypeMe;
            logo_url = [LTPCacheManager shareInstance].getUserInfoModel.doctor.credential.figure_file.url;;
        } else if ([receiver_type isEqualToString:@"doctor"]) {
            model.messageSenderType = MessageSenderTypeOther;
            logo_url = [[[dict valueForKey:@"sender"] valueForKey:@"avatar"] valueForKey:@"url"];
        }
        model.logoUrl = logo_url;
        if ([images count] > 0) {
            NSDictionary *img_dic = images[0];
            model.imageUrl = [img_dic valueForKey:@"url"];
            model.messageType = MessageTypeImage;
        }else {
            model.messageType = MessageTypeText;
        }
        model.messageText = content;
        [_dataArray insertObject:model atIndex:0];
    }
    
    [_tableView reloadData];
    
    [_tableView scrollToBottomAnimated:NO];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];

    self.pageIndex = 1;
    
    self.title = self.chatPersonName;
    
    _dataArray = [NSMutableArray arrayWithCapacity:0];
    
    _tableView.backgroundColor = [[UIColor alloc] initWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
    
    
    _bigImageView = [[CSBigView alloc] init];
    _bigImageView.frame = [UIScreen mainScreen].bounds;
    
    _ev = [[EmojiView alloc] initWithFrame:CGRectMake(0, ScreenHight - 180, ScreenWidth, 180)];
    _ev.hidden = YES;
    _ev.delegate = self;
    [self.view addSubview:_ev];
    
    
    _tableView.separatorColor = [UIColor clearColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    
    [self requestChatList];

}

-(void)keyboardWillShow:(NSNotification *)aNotification
{
    _ev.hidden = YES;
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    _tableBottomConstraint.constant = 44 + height;
    UIView *vi = [self.view viewWithTag:100];
    CGRect rec = vi.frame ;
    rec.origin.y = _nowHeight - height;
    vi.frame = rec;
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    _ev.hidden = YES;
    _tableBottomConstraint.constant = 44;
    UIView *vi = [self.view viewWithTag:100];
    vi.frame = CGRectMake(0, _nowHeight, [UIScreen mainScreen].bounds.size.width, 44);
}
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    UIView *vi = [self.view viewWithTag:100];
    if (!vi)
    {
        _nowHeight =  _tableView.frame.size.height;
        [self bottomView];
    }
    
}

#pragma mark -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CSMessageCell *cell=[CSMessageCell cellWithTableView:tableView messageModel:_dataArray[indexPath.row]];
    cell.delegate = self;
//    cell
    cell.backgroundColor = [[UIColor alloc] initWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CSMessageModel *messageModel = _dataArray[indexPath.row];
    if (messageModel.messageType == MessageTypeImage) {
        NSString *img_str = IMG_URL(messageModel.imageUrl);
        
        UIImage *image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:img_str];
        if (!image) {
            [self downloadImage:messageModel.imageUrl forIndexPath:indexPath];
        }
    }
    return [messageModel cellHeight];
}


- (void)downloadImage:(NSString *)imageURL forIndexPath:(NSIndexPath *)indexPath {
    
    // 利用 SDWebImage 框架提供的功能下载图片
    
    CSMessageModel *model = _dataArray[indexPath.row];
    if (model.messageType == MessageTypeImage) {
        
        NSString *imageURL = IMG_URL(model.imageUrl);

        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:imageURL] options:SDWebImageDownloaderUseNSURLCache progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            
        } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
            if (image) {
                
                [[SDImageCache sharedImageCache] storeImageDataToDisk:UIImagePNGRepresentation(image) forKey:imageURL];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableView reloadData];
                    [self.tableView scrollToBottomAnimated:NO];
                    
                });
            }

            
        }];
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}
- (void)messageCellSingleClickedWith:(CSMessageCell *)cell
{
    
    [self.view endEditing:YES];
    
    
    if (_ev.hidden == NO)
    {
        _ev.hidden = YES;
        _tableBottomConstraint.constant = 44;
        UIView *vi = [self.view viewWithTag:100];
        vi.frame = CGRectMake(0, _nowHeight, [UIScreen mainScreen].bounds.size.width, 44);
    }
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    CSMessageModel *model = _dataArray[indexPath.row];
    if (model.messageType == MessageTypeVoice)
    {
        [[CSRecord ShareCSRecord] playRecord];
        
        if ([_selectIndex isEqual: indexPath] == NO)
        {
            
            CSMessageCell *cell1 = [self.tableView cellForRowAtIndexPath:_selectIndex];
            [cell1 stopVoiceAnimation];
            
            _selectIndex = indexPath;
            [cell startVoiceAnimation];
        }
        else
        {
            if (cell.voiceAnimationImageView.isAnimating)
            {
                [cell stopVoiceAnimation];
            }
            else
            {
                [cell startVoiceAnimation];
            }
        }
    }
    else if (model.messageType == MessageTypeImage)
    {
        _bigImageView.bigImageView.image = model.imageSmall;
        _bigImageView.show = YES;
        
//        [[UIApplication sharedApplication].keyWindow bringSubviewToFront:_bigImageView];
    }
    
}

-(void)bottomView
{
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, _nowHeight, [UIScreen mainScreen].bounds.size.width, 44)];
    bgView.tag = 100;
    bgView.backgroundColor = [[UIColor alloc] initWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    bgView.layer.masksToBounds = YES;
    bgView.layer.borderColor = [[UIColor alloc] initWithRed:235/255.0 green:235/255.0 blue:235/255.0 alpha:1].CGColor;
    bgView.layer.borderWidth = 1;
    [self.view addSubview:bgView];
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(49, 0, bgView.bounds.size.width - 49 - 74, 44)];
    textView.delegate = self;
    textView.tag = 101;
    textView.returnKeyType = UIReturnKeySend;
    textView.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
//    textView.text = @"hello world";
    textView.placeholder = @"";
    [bgView addSubview:textView];
    self.textView = textView;
    
    // select images
    UIButton *recordBtn = [[UIButton alloc] init];
    recordBtn.frame = CGRectMake(10, 5, 34, 34);
    [recordBtn setImage:[UIImage imageNamed:@"bg_wait"] forState:UIControlStateNormal];
    [recordBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    recordBtn.tag = 13;
//    [recordBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
//    [recordBtn addTarget:self action:@selector(leaveBtnClicked:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchUpOutside];
//    [recordBtn addTarget:self action:@selector(touchDown:)forControlEvents: UIControlEventTouchDragInside];
    [bgView addSubview:recordBtn];
    
    UIImage *highLImg = [UIImage imageWithColor:[UIColor colorWithHexString:@"#999999"]];
    UIImage *normalImg = [UIImage imageWithColor:[UIColor colorWithHexString:@"#F7941E"]];
    
    UIButton *postBtn = [[UIButton alloc] init];
    postBtn.frame = CGRectMake(bgView.frame.size.width - 64, 5, 54, 34);
    [postBtn.layer setMasksToBounds:YES];
    [postBtn.layer setCornerRadius:10.0];
    [postBtn setTitle:@"发送" forState:UIControlStateNormal];
    [postBtn setBackgroundImage:normalImg forState:UIControlStateNormal];
    [postBtn setBackgroundImage:highLImg forState:UIControlStateHighlighted];
//    [postBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [postBtn addTarget:self action:@selector(sendMessageAction) forControlEvents:UIControlEventTouchUpInside];
    postBtn.tag = 12;
    [bgView addSubview:postBtn];

//    UIButton *emojiBtn = [[UIButton alloc] init];
//    emojiBtn.frame = CGRectMake(bgView.frame.size.width - 83, 5, 34, 34);
//    [emojiBtn setBackgroundImage:[UIImage imageNamed:@"emoji"] forState:UIControlStateNormal];
//    [emojiBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
//    emojiBtn.tag = 12;
//    [bgView addSubview:emojiBtn];
//
//    UIButton *imageBtn = [[UIButton alloc] init];
//    imageBtn.frame = CGRectMake(bgView.frame.size.width - 39, 5, 34, 34);
//    [imageBtn setBackgroundImage:[UIImage imageNamed:@"image"] forState:UIControlStateNormal];
//    [imageBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
//    imageBtn.tag = 13;
//    [bgView addSubview:imageBtn];
    
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"])
    {
        if (textView.text.length == 0)
        {
            return NO;
        }
        [self sendMessageAction];
        return NO;
    }
    
    return YES;
}

- (NSString *)nowDateFormatHHmm
{
    NSInteger hour = [[NSDate date] hour];
    NSInteger minute = [[NSDate date] minute];
    
    NSString *dateString = [NSString stringWithFormat:@"%@:%@%@", [NSNumber numberWithInteger:hour], minute<10?@"0":@"",[NSNumber numberWithInteger:minute]];
    return dateString;
}

#pragma mark Send Message Action
- (void)sendMessageAction
{
    if (self.textView.text.length == 0)
    {
        return;
    }
    
    [self requestPostMessage:nil];
    
    CSMessageModel *model = [[CSMessageModel alloc] init];
    model.showMessageTime=NO;
    model.messageSenderType = MessageSenderTypeMe;
    model.messageType = MessageTypeText;
    model.messageText = self.textView.text;
    model.messageTime = [self nowDateFormatHHmm];
    [_dataArray addObject:model];
    [_tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:_dataArray.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:_dataArray.count - 1 inSection:0]
                                animated:YES
                          scrollPosition:UITableViewScrollPositionBottom];
    self.textView.text = @"";
}

static int iiii = 0;
- (void)touchDown:(UIButton *)btn
{
    if (iiii == 0)
    {
        [[CSRecord ShareCSRecord] beginRecord];
        iiii = 1;
    }
    
}
- (void)leaveBtnClicked:(UIButton *)btn
{
    iiii = 0;
    NSLog(@"松开了");
    [[CSRecord ShareCSRecord] endRecord];
}
- (void)btnClicked:(UIButton *)btn
{
    [self.view endEditing:YES];
    _ev.hidden = YES;
    _tableBottomConstraint.constant = 44;
    UIView *vi = [self.view viewWithTag:100];
    vi.frame = CGRectMake(0, _nowHeight, [UIScreen mainScreen].bounds.size.width, 44);
    switch (btn.tag)
    {
        case 11:
            
            break;
        case 12:
            
        {
            
            _ev.hidden = NO;
            _tableBottomConstraint.constant = 44 + 180;
            UIView *vi = [self.view viewWithTag:100];
            CGRect rec = vi.frame ;
            rec.origin.y = _nowHeight - 180;
            vi.frame = rec;

        }
            
            break;
        case 13:
            {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
                [alertController addAction:[UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                        
                        //图片选择是相册（图片来源自相册）
                        
                        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
                        
                        //设置代理
                        
                        picker.delegate=self;
                        
                        //模态显示界面
                        
                        [self presentViewController:picker animated:YES completion:nil];
                        
                    }
                    
                    else {
                        
                        NSLog(@"不支持相机");
                        
                    }
                    

                    NSLog(@"点击确认");
                    
                }]];
                [alertController addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
                    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                        
                        //图片选择是相册（图片来源自相册）
                        
                        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                        
                        //设置代理
                        
                        picker.delegate=self;
                        
                        //模态显示界面
                        
                        [self presentViewController:picker animated:YES completion:nil];
                        
                        
                        
                    }
                    
                    NSLog(@"点击确认");
                    
                }]];
                [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                    [self dismissViewControllerAnimated:YES completion:nil];
                    NSLog(@"点击取消");
                    
                }]];
                
                [self presentViewController:alertController animated:YES completion:nil];
                
            }
            break;
        default:
            break;
    }
    NSLog(@"呀！我这个按钮别点击了！");
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
     if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary)
     {
        UIImage * image =info[UIImagePickerControllerOriginalImage];
        image = [self imageScaleForSiYue:image];

         [self requestUploadImage:image];
         
        [self dismissViewControllerAnimated:YES completion:nil];
     }
   else if (picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        UIImage * image =info[UIImagePickerControllerOriginalImage];
        image = [self imageScaleForSiYue:image];
        [self requestUploadImage:image];
        
//        CSMessageModel * model = [[CSMessageModel alloc] init];
//        model.showMessageTime=YES;
//        model.messageSenderType = MessageSenderTypeMe;
//        model.messageType = MessageTypeImage;
//        model.imageSmall = image;
//        model.messageTime = [self nowDateFormatHHmm];
//        [_dataArray addObject:model];
//
//        [_tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:_dataArray.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
//        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:_dataArray.count - 1 inSection:0]
//                                    animated:YES
//                              scrollPosition:UITableViewScrollPositionMiddle];
//
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

-(UIImage *)imageScaleForSiYue:(UIImage*)image
{
    float XIANZHIWIDTH = 640;
    float imgWidth = image.size.width;
    float imgHeight = image.size.height;
    if (imgWidth==imgHeight) {
        if (imgWidth>XIANZHIWIDTH) {
            return [ChatViewController imageWithImageSimple:image scaledToSize:CGSizeMake(XIANZHIWIDTH, XIANZHIWIDTH)];
        }
    }
    if (imgWidth>imgHeight) {
        if (imgHeight>XIANZHIWIDTH) {
            float widthR = XIANZHIWIDTH/(image.size.height/image.size.width);
            return [ChatViewController imageWithImageSimple:image scaledToSize:CGSizeMake(widthR, XIANZHIWIDTH)];
        }
    }else {
        if (imgWidth>XIANZHIWIDTH) {
            float heightR = XIANZHIWIDTH/(image.size.width/image.size.height);
            return [ChatViewController imageWithImageSimple:image scaledToSize:CGSizeMake(XIANZHIWIDTH, heightR)];
        }
    }
    return image;
}

+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
-(void)insertImageUrl:(NSString *)url
{
    CSMessageModel * model = [[CSMessageModel alloc] init];
    model.showMessageTime=NO;
    model.messageSenderType = MessageSenderTypeMe;
    model.messageType = MessageTypeImage;
//    model.imageSmall = image;
    model.imageUrl = url;
    model.messageTime = [self nowDateFormatHHmm];
    [_dataArray addObject:model];
    
    [_tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForItem:_dataArray.count - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:_dataArray.count - 1 inSection:0]
                                animated:YES
                          scrollPosition:UITableViewScrollPositionBottom];
    
}


// 上传图片 开始
- (void)requestUploadImage:(UIImage *)image
{
    [MMProgressHUD showWithTitle:@"上传图片中"];
    //1.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    NSString *token = [LTPCacheManager shareInstance].token;
    token = [NSString stringWithFormat:@"Bearer %@",token];
    
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"authorization"];
    
    NSString *uploadUrl = [NSString stringWithFormat:@"%@%@", BASE_URL, @"/common/file/upload"];
    [manager POST:uploadUrl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"file.jpg" mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //打印上传进度
        CGFloat progress = 100.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount;
        NSLog(@"%.2lf%%", progress);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MMProgressHUD updateProgress:progress withStatus:@"上传中"];
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject
                                                            options:NSJSONReadingMutableContainers
                                                              error:nil];
        ImageInfo *imgModel = [ImageInfo modelWithDictionary:dic[@"data"][@"file"]];
        NSLog(@"上传成功：%@",imgModel);
        [self requestPostMessage:[NSNumber numberWithInteger:imgModel.id]];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MMProgressHUD dismissWithSuccess:@"上传成功"];
            [self insertImageUrl:imgModel.url];

//            [self.tableView reloadData];
        });
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        dispatch_async(dispatch_get_main_queue(), ^{
            [MMProgressHUD dismissWithError:@"上传失败"];
        });
        NSLog(@"上传失败：%@",error);
    }];
}


- (void)showBigImage
{
    
}

#pragma mark - EmojiViewDelegate
- (void)emojiClicked:(NSString *)strEmoji {
    UITextView *tv = [self.view viewWithTag:101];
    tv.text = [tv.text stringByAppendingString:strEmoji];
    
}

- (void)messageUpdateImageFrame
{
//    if (flag == 1) {
//        [self.tableView reloadData];
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
